/*
 * @Overview     : JsBridge Methods
 * @Author       : Zi Jun
 * @Email        : zijun2030@163.com
 * @Date         : 2021-03-10 16:16:42
 * @LastEditTime : 2021-03-17 10:03:21
 * @LastEditors  : Zi Jun
 * @FilePath     : \simple-vite\src\utils\js-bridge\methods.ts
 * @Mark         : 命名规范：
 *                  1. 调用APP注册的方法，形式为：app...
 *                  2. 注册JS注册的方法，形式为：js...
 */

import { callHandler, registerHandler } from './index';
import store from '@/store';

/**
 * @description: 获取用户信息
 * @return {*}
 */
export const appGetUserInfo = async (): Promise<void> => {
	return new Promise<void>((resolve) => {
		callHandler('getUserInfo', '', (data: any) => {
			const { token, userInfo } = JSON.parse(data);
			const loginData = {
				userInfo,
				accessToken: token,
			};
			store.dispatch('user/loginSave', loginData);
			resolve();
		});
	});
};

/**
 * @description: 跳转APP登录
 * @return {*}
 */
export const appLogin = async (): Promise<void> => {
	await callHandler('login');
};

/**
 * @description: 关闭H5页面
 * @return {*}
 */
export const appCloseWebView = async (): Promise<void> => {
	await callHandler('closeWebView');
};

/**
 * @description: H5跳转到APP页面
 * @param {*} data 给app的数据
 * @return {*}
 * @example： appJumpNativePage({type: x, url: 'xxx'}) // 跳转原生xxx页面
 */
export const appJumpNativePage = async (data: Record<string, unknown>): Promise<void> => {
	await callHandler('jumpPage', data);
};

/**
 * @description: H5控制APP跳转到APP指定页面
 * @param {string} name H5注册事件名称
 * @param {*} sendData 给app的数据
 * @return {*}
 * @example：jsJumpNativePage('jsJumpPage', { type: 'x', value: 'xxx' }); // 跳转APP某页面
 */
export const jsJumpNativePage = async (
	name: string,
	sendData: Record<string, unknown>,
): Promise<void> => {
	await registerHandler(name, (_data, responseCallback) => {
		responseCallback(JSON.stringify(sendData));
	});
};
